<template>
  <view class="download-demo-page">
    <view class="page-header">
      <text class="header-title">文件下载演示（图片+视频）</text>
    </view>

    <view class="main-content">
      <view class="module-card">
        <text class="module-title">图片下载</text>
        
        <button class="download-btn image-btn" @click="downloadImage">
          <uni-icons type="download" size="18" color="#fff"></uni-icons>
          <text class="btn-text">下载并显示图片</text>
        </button>

        <view class="progress-container" v-if="imageProgress > 0 && imageProgress < 100">
          <progress :percent="imageProgress" stroke-width="5" color="#67c23a" background-color="#e6f7ef" />
          <text class="progress-text">图片下载进度：{{ imageProgress }}%</text>
        </view>

        <view class="error-view" v-if="imageError">
          <uni-icons type="warn" size="20" color="#f56c6c"></uni-icons>
          <text class="error-text">{{ imageError }}</text>
          <button class="retry-btn" @click="downloadImage">重试</button>
        </view>

        <view class="image-wrap" v-if="imagePath">
          <image :src="imagePath" mode="aspectFit" class="display-image"></image>
          <text class="file-tip">图片下载完成</text>
        </view>

        <view class="init-tip" v-if="!imagePath && !imageProgress && !imageError">
          <text class="init-text">点击按钮开始下载图片</text>
        </view>
      </view>

      <view class="module-card">
        <text class="module-title">视频下载（稳定方案）</text>
        
  
        <button class="download-btn video-btn" @click="useLocalVideo">
          <uni-icons type="video" size="18" color="#fff"></uni-icons>
          <text class="btn-text">使用本地测试视频</text>
        </button>

        <button class="download-btn video-btn备选" @click="downloadPublicVideo">
          <uni-icons type="download" size="18" color="#fff"></uni-icons>
          <text class="btn-text">下载公开测试视频</text>
        </button>

        <view class="progress-container" v-if="videoProgress > 0 && videoProgress < 100">
          <progress :percent="videoProgress" stroke-width="5" color="#3a8ee6" background-color="#e6f0fa" />
          <text class="progress-text">视频下载进度：{{ videoProgress }}%</text>
        </view>

        <view class="error-view" v-if="videoError">
          <uni-icons type="warn" size="20" color="#f56c6c"></uni-icons>
          <text class="error-text">{{ videoError }}</text>
          <button class="retry-btn" @click="downloadPublicVideo">重试</button>
        </view>

        <view class="video-wrap" v-if="videoPath">
          <video :src="videoPath" controls class="display-video" poster="https://picsum.photos/800/400"></video>
          <text class="file-tip">视频已就绪</text>
        </view>

        <view class="init-tip" v-if="!videoPath && !videoProgress && !videoError">
          <text class="init-text">选择任意方案即可播放视频</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      imagePath: '',
      imageProgress: 0,
      imageError: '',
      imageUrl: 'https://picsum.photos/800/500',

      videoPath: '',
      videoProgress: 0,
      videoError: '',
      publicVideoUrl: 'https://github.com/zhihuifan1999/test-video/raw/main/small-video.mp4'
    };
  },
  methods: {
    downloadImage() {
      this.imageProgress = 0;
      this.imageError = '';
      this.imagePath = '';

      uni.downloadFile({
        url: this.imageUrl,
        header: this.getCommonHeader(),
        onProgressUpdate: (res) => {
          this.imageProgress = res.progress;
          this.logProgress('图片', res);
        },
        success: (res) => {
          if (res.statusCode === 200) this.imagePath = res.tempFilePath;
          else this.imageError = `图片下载失败，状态码：${res.statusCode}`;
        },
        fail: () => {
          this.imageError = '图片请求失败，请检查网络';
        }
      });
    },

    useLocalVideo() {
      this.videoError = '';
      this.videoProgress = 0;
      this.videoPath = 'https://github.com/zhihuifan1999/test-video/raw/main/small-video.mp4';
      console.log('使用本地测试视频，路径：', this.videoPath);
    },

    downloadPublicVideo() {
      this.videoProgress = 0;
      this.videoError = '';
      this.videoPath = '';

      uni.downloadFile({
        url: this.publicVideoUrl,
        header: this.getCommonHeader(),
        onProgressUpdate: (res) => {
          this.videoProgress = res.progress;
          this.logProgress('视频', res);
        },
        success: (res) => {
          if (res.statusCode === 200) {
            this.videoPath = res.tempFilePath;
            console.log('视频下载成功，路径：', res.tempFilePath);
          } else {
            this.videoError = `视频下载失败，状态码：${res.statusCode}`;
          }
        },
        fail: (err) => {
          this.videoError = '视频请求失败，建议选择「本地测试视频」方案';
          console.error('视频下载失败：', err);
        }
      });
    },

    getCommonHeader() {
      return {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36',
        'Accept': '*/*',
        'Referer': 'https://github.com/'
      };
    },

    logProgress(type, res) {
      const loaded = this.formatSize(res.totalBytesWritten);
      const total = this.formatSize(res.totalBytesExpectedToWrite);
      console.log(`${type}进度：${res.progress}%，已下载：${loaded}，总大小：${total}`);
    },

    formatSize(bytes) {
      if (bytes < 1024) return bytes + ' B';
      else if (bytes < 1048576) return (bytes / 1024).toFixed(1) + ' KB';
      else return (bytes / 1048576).toFixed(1) + ' MB';
    }
  }
};
</script>

<style scoped>
.download-demo-page {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding-bottom: 40rpx;
}

.page-header {
  height: 44px;
  line-height: 44px;
  background-color: #409eff;
  padding: 0 16px;
  display: flex;
  align-items: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}
.header-title {
  color: #fff;
  font-size: 18px;
  font-weight: 500;
}

.main-content {
  padding: 30rpx 24rpx;
  display: flex;
  flex-direction: column;
  gap: 30rpx;
}

.module-card {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx 24rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}
.module-title {
  font-size: 16px;
  color: #303133;
  font-weight: 500;
  margin-bottom: 25rpx;
  display: block;
}

.download-btn {
  width: 360rpx;
  height: 80rpx;
  line-height: 80rpx;
  border-radius: 40rpx;
  font-size: 15px;
  margin: 0 auto 20rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10rpx;
  transition: all 0.3s ease;
}
.download-btn:hover {
  transform: translateY(-2rpx);
  box-shadow: 0 6rpx 16rpx rgba(0, 0, 0, 0.1);
}
.image-btn {
  background-color: #67c23a;
  color: #fff;
}
.video-btn {
  background-color: #3a8ee6;
  color: #fff;
}
.video-btn备选 {
  background-color: #909399;
  color: #fff;
}

.progress-container {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 12rpx;
  margin-bottom: 20rpx;
}
.progress-text {
  text-align: center;
  font-size: 13px;
  font-weight: 500;
}
.image-btn + .progress-container .progress-text {
  color: #67c23a;
}
.video-btn + .progress-container .progress-text {
  color: #3a8ee6;
}

.error-view {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15rpx;
  padding: 20rpx 0;
  text-align: center;
}
.error-text {
  color: #f56c6c;
  font-size: 13px;
  line-height: 1.5;
}
.retry-btn {
  width: 140rpx;
  height: 56rpx;
  line-height: 56rpx;
  background-color: #409eff;
  color: #fff;
  border-radius: 28rpx;
  font-size: 13px;
}

.image-wrap {
  width: 100%;
  height: 300rpx;
  background-color: #fafafa;
  border-radius: 12rpx;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  margin-top: 10rpx;
}
.display-image {
  width: 90%;
  height: 90%;
  object-fit: contain;
}

.video-wrap {
  width: 100%;
  background-color: #fafafa;
  border-radius: 12rpx;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  position: relative;
  margin-top: 10rpx;
}
.display-video {
  width: 100%;
  height: 300rpx;
  background-color: #000;
}

.file-tip {
  position: absolute;
  bottom: 15rpx;
  background-color: rgba(0, 0, 0, 0.5);
  color: #fff;
  font-size: 11px;
  padding: 5rpx 18rpx;
  border-radius: 18rpx;
}

.init-tip {
  text-align: center;
  color: #c0c4cc;
  font-size: 13px;
  padding: 30rpx 0;
}
</style>